package org.grails.facebook_graph_integration;

class FacebookIntegrationController {

	def facebookGraphService

    def index = {
    	def friends = facebookGraphService.getFriends()
    	def profile = facebookGraphService.getFacebookProfile()
    	[ "friends" : friends, "profile" : profile ]
    }
    
    def auth = {
    	// Check Null
    	if ( session.facebook == null || !session.facebook.uid ) {
    		println "Facebook UID Available!"
    		return;
    	} 
    
    	// Print Facebook UID
    	println "Faceboook UID: " +  {session.facebook.uid}
    	
    	// Define Value
    	def value = session.facebook.uid;
    	if ( session.facebook.uid instanceof java.util.List ) {
    		try {
    			for ( i in session.facebook.uid ) {
    				value = i;
    			} 
    		} catch (Throwable t) {
    			t.printStackTrace();
    		} 
    	}
    
		// Try to find current one    	
    	def fb = FacebookUser.list( "uid" : value );
    	if ( fb == null || fb.size() == 0 ) {
    		fb = new FacebookUser();
    		fb.uid = session.facebook.uid;
    		fb = fb.save( flush : true );
    		println "Saved Facebook User: " + fb;
    	} 

		// Return Url
    	redirect(uri:"/");
    }
    
}
